<?php
namespace Partner\Controller;

use Utuo\BackgroundController;

/**
 * 产品栏目管理
 * @author song
 */
class ProductCategoryController extends BackgroundController {
	
	private $tplTypes = array('page','cate','list','show');

	public function _initialize() {
		$this->setControllerTitle("栏目管理");
		$this->setActionTitle(array(
			'index' => '栏目列表',
			'add' => '栏目添加',
			'modify' => '修改栏目',
			'recycle' => '回收站'
		));
		$this->setActionNav(array(
			'index',
			'add',
			'recycle'
		));
	}
	
	/**
	 * 栏目列表
	 */
	public function indexAction() {
		$d = D("ProductCategory");
		$tree = $d->getTree(0, $this->aid, 'id,pid,name,sort,status,is_deleted,logo,level,has_child');
		$categoryLists = $d->getTreeList($tree);
		$this->assign('productCategoryLists', $categoryLists);
		$this->display();
	}
	
	/**
	 * 添加栏目
	 */
	public function addAction() {
		C("TOKEN_ON", true);
		$d = D("ProductCategory");
		$pid = I("get.id",0,"intval");
		$categoryOptions = $d->getOptionTree(null, $this->aid, 'id,pid,name');
		$visibleOptions = $this->getRadio('visible', array('0'=>'显示', '1'=>'隐藏'), 0);
		/*页面输出*/
		$category['visibleOptions'] = $visibleOptions;
		$this->assign("productCategoryOptions", $this->getOption($categoryOptions, "$pid", '==顶级栏目=='));
		$this->assign("typesOptions", $this->getOption($d->types, 'list', '==请选择栏目类型=='));
		$this->assign("visibleOptions", $visibleOptions);
		$this->display();
	}
	
	/**
	 * 提交添加栏目
	 */
	public function addPostAction() {
		C("TOKEN_ON", true);
		$d = D("ProductCategory");
		if ($d->create()) {
			if( $d->pid ){
				$m = M("ProductCategory");
				$pLevel = $m->where("id=%d", $d->pid)->getField("level");
				$d->level = $pLevel + 1;
				$m->where("id=%d",$d->pid)->setField('has_child',1);
			}
			if ($d->add()) {
				$this->ajaxSuccess();
			} else {
				$this->ajaxError($d->getError());
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	/**
	 * 修改栏目
	 */
	public function modifyAction() {
		$id = I("id", 0, "intval");
		$d = D("ProductCategory");
		$this->checkAdmin(null, $d, "partner");
		$category = $this->getOneById("ProductCategory");
		$categoryOptions = $d->getOptionTree($id, $this->aid, 'id,pid,name');
		$visibleOptions = $this->getRadio('visible', array('0'=>'显示', '1'=>'隐藏'), $category['visible']*1);
		/*获得模板配置*/
		$tplConfig = unserialize($category['tpl_config']);
		$partnerProduct = M("PartnerProduct")->where(array('pid'=>$this->aid))->find();
		foreach ($this->tplTypes as $v) {
			$tplsList = array();
			$partnerProduct['theme'] = $partnerProduct['theme']*1;
			if( $partnerProduct['theme'] ) {
				/* 获得当前主题的各个模板类型可设置的模板 */
				$tpls = M("ThemeTplAuth a")->join("__THEME_TPL__ b on a.tpl_id=b.id")->where("b.is_deleted=0 and b.status=1 and b.type='%s' and find_in_set({$partnerProduct['theme']},a.theme)", $v)->field('b.id,b.name')->select();
				foreach ( $tpls as $v0) $tplsList[$v0['id']] = $v0['name'];
			}
			$category[$v."TplOptions"] = $this->getOption($tplsList, $tplConfig[$v], '==默认模板==');
		}
		/*页面输出*/
		$category['categoryOptions'] = $this->getOption($categoryOptions, $category['pid'], '==顶级栏目==');
		$category['visibleOptions'] = $visibleOptions;
		$this->assign("typesOptions", $this->getOption($d->types, $category['type'], '==请选择栏目类型=='));
		$this->assign("productCategory", $category);
		$this->display();
	}
	
	/**
	 * 提交修改栏目
	 */
	public function modifyPostAction() {
		$id = I("id", 0, "intval");
		$d = D("ProductCategory");
		if ($d->create()) {
			/*父栏是否有变动*/
			$category = $this->getOneById("ProductCategory"); $d->pid*=1;
			if($category['pid'] != $d->pid) { // 父栏有变动
				$d->changeParentNode($category, 'id,pid,name');
				$d->getError() && $this->ajaxError($d->getError());
			}
			if (false !== $d->save()) {
				$this->ajaxSuccess();
			}
		}
		$this->ajaxError($d->getError());
	}
	
	/**
	 * 回收站
	 */
	public function recycleAction() {
		$page = $this->getPage();
		$pagesize = $this->getPageSize();
		$condition = array(
				'is_deleted' => 1,
				"partner" => $this->aid
		);
		$articleCategoryLists = M("ProductCategory")->where($condition)->limit($pagesize)->page($page)->order('id DESC')->select();
		$articleCategoryCount = M("ProductCategory")->where($condition)->count();
		$this->assign('productCategoryLists', $articleCategoryLists);
		$this->showPage($articleCategoryCount, $pagesize);
		$this->display();
	}
	
	/**
	 * 恢复栏目
	 */
	public function restorePostAction() {
		$m = D("ProductCategory");
		$category = $this->getOneById("ProductCategory");
		// 有父栏先恢复父栏
		if($category['pid']){
			$parentCategory = $m->find($category['pid']);
			if($parentCategory['is_deleted']){
				$this->ajaxError("存在父栏目必须先恢复父栏目.");
			}
		}
		$this->addEventListener("afterRestore", function($e, $scope) { call_user_method("checkHasChild", $scope);  });
		$this->ajaxRestore("ProductCategory");
	}
	
	/**
	 * 移除栏目
	 */
	public function removePostAction() {
		$id = I('id', 0, 'intval');
		$m = D("ProductCategory");
		// 有子栏则不能移除
		if($m->where("pid=%d and is_deleted=0",$id)->count()) {
			$this->ajaxError("存在子栏目未能移除,请确认子栏目已移除.");
		}
		// 栏目下有商品未能移除
		$result = M("ProductGoods")->where("cat_id=%d and is_deleted=0", $id)->count();
		if($result > 0) $this->ajaxError("栏目下存在{$result}件商品未能移除");
		$this->addEventListener("afterRemove", function($e, $scope) { 
			call_user_method("checkHasChild", $scope);
		});
		$this->ajaxRemove("ProductCategory");
	}
	
	/**
	 * 删除栏目
	 */
	public function deletePostAction() {
		$id = I('id', 0, 'intval');
		$m = D("ProductCategory");
		// 有子栏则不能删除
		if($m->where("pid=%d and is_deleted=1",$id)->count()) {
			$this->ajaxError("存在子栏目未能删除.");
		}
		// 设置父栏无孩子
		$category = D("ProductCategory")->where("id=%d",$id)->find();
		if($category['pid']) D("ProductCategory")->where("id=%d",$category['pid'])->setField('has_child',0);
		// 删除栏目中的所有商品
		$ids = M('ProductGoods')->where("cat_id=%d and is_deleted=1", $id)->getField("id", true); 
		M('ProductGoods')->where(array('id'=>array('in', $ids)))->delete();
		M('ProductGoodsConfig')->where(array('id'=>array('in', $ids)))->delete();
		$this->ajaxDelete("ProductCategory");
	}
	
	/**
	 * 设置状态
	 */
	public function setStatusPostAction() {
		$id = I("id", 0, "intval");
		$status = I("status", 0, "intval");
		$category = D("ProductCategory");
		if ($category->where("id={$id}")->setField("status", 1 - $status)) {
			$this->ajaxSuccess();
		} else {
			$this->ajaxError($category->getError());
		}
	}
	
	// 检查栏目父类是否有孩子
	public function checkHasChild($pid) {
		$id = I('id', 0, "intval");
		$pid or $pid = M('ProductCategory')->where("id=%d", $id)->getField("pid");
		if($pid){
			$has_child = M('ProductCategory')->where("pid=%d and is_deleted=0", $pid)->count()?1:0;
			M('ProductCategory')->where("id=%d", $pid)->setField("has_child", $has_child);
		}
	}
	
}